package com.github.tommas.decompiler;

import com.strobel.assembler.metadata.ArrayTypeLoader;
import com.strobel.decompiler.DecompilerSettings;
import com.strobel.decompiler.PlainTextOutput;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class ProcyonDecompiler implements Decompiler {
    private final String root;
    public ProcyonDecompiler(String rootDir) {
        root = rootDir;
    }

    @Override
    public void decompile(String className, byte[] classfileBuffer) {
        int idx = className.lastIndexOf("/");
        String filename = "";
        String path = root;
        if (idx < 0) {
            filename = className + ".java";
        } else {
            filename = className.substring(idx + 1) + ".java";
            path += File.separator + className.substring(0, idx);
        }

        File dir = new File(path);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                throw new RuntimeException(String.format("Can not create directory %s", path));
            }
        }

        File file = new File(path + File.separator + filename);
        Writer writer = null;
        try {
            writer = new FileWriter(file, false);
            DecompilerSettings settings = DecompilerSettings.javaDefaults();
            settings.setTypeLoader(new ArrayTypeLoader(classfileBuffer));
            com.strobel.decompiler.Decompiler.decompile(className, new PlainTextOutput(writer), settings);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
